package com.tte.common.java8;

import com.tte.common.model.po.User;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * OptionalTest
 * @Author DongWH
 * @Date 2024/7/12 10:13
 */
public class OptionalTest {
    public static void main(String[] args) {
        User user = null;
        System.out.println(Optional.ofNullable(user).map(User::getcCode).orElse("默认值"));
//        System.out.printf(Optional.ofNullable(user).map(User::getcCode).orElseGet(user::getcLoginName));
        System.out.println(Objects.isNull(user));//true
        User user2 = new User();
        System.out.println(Objects.isNull(user2));//false
        System.out.println( Optional.ofNullable(user).isPresent());//是否包含一个值:false
        //安全地获取值
        String name1 =  Optional.ofNullable(user).orElse(new User("张三","男","",19,new Date())).getcName();
        String name2 =  Optional.ofNullable(user).orElseGet(() -> new User("张三","男","",19,new Date())).getcName();
        String name = Optional.ofNullable(user).flatMap(u -> Optional.ofNullable(u.getcName())).orElse("默认值");
    }
}